package ymodels

import (
	"errors"
	"time"
)

// Date the date format time
type Date time.Time

// MarshalJSON implements the json.Marshaler interface.
func (d Date) MarshalJSON() ([]byte, error) {
	t := time.Time(d)
	if y := t.Year(); y < 0 || y >= 10000 {
		return nil, errors.New("Time.MarshalJSON: year ouside of range [0,9999]")
	}

	f := "2006-01-02"
	b := make([]byte, 0, len(f)+2)
	b = append(b, '"')
	b = t.AppendFormat(b, f)
	b = append(b, '"')
	return b, nil
}

// UnmarshalJSON implements the json.Unmarshaler interface.
func (d *Date) UnmarshalJSON(data []byte) error {
	if string(data) == "null" {
		return nil
	}

	t, err := time.Parse(`"2006-01-02"`, string(data))
	*d = Date(t)
	return err
}
